<?php

namespace App\Components;

use App\Components\Tools;

/**
 * 抖音工具类
 */
class DyToools
{
    //抖音调用接口方法
    private $clientKey = '';
    private $clientSecret = '';
    private $url = '';
    private $redirectUri = '';
    private $scope = '';

    function __construct()
    {
        $this->clientKey = Tools::getOneconfig("/config/third.json", array('douyin', 'dy_client_key'));
        $this->clientSecret = Tools::getOneconfig("/config/third.json", array('douyin', 'dy_client_secret'));
        $this->url = Tools::getOneconfig("/config/third.json", array('douyin', 'dy_url'));
        $this->redirectUri = Tools::getOneconfig("/config/third.json", array('douyin', 'dy_bank_url'));

        $this->scope = 'video.create,video.delete,video.data,video.list,im.share,video.search,video.search.comment,aweme.share,user_info,';
        $this->scope .= 'following.list,fans.list,fans.check,renew_refresh_token,mobile_alert,mobile,video.comment,enterprise.data,enterprise.im,';
        $this->scope .= 'item.comment,data.external.user,data.external.item,fans.data,star_top_score_display,star_tops,star_author_score_display,';
        $this->scope .= 'data.external.sdk_share,data.external.fans_favourite,poi.search,micapp.is_legal,incremental_authorization';
    }


    /**    刷新access_token
     *    流程 ： 其他接口返回 2190008 或 10008   需要调用此方法
     *    如果此方法返回  10010    需要调用 refresh_token  方法刷新
     */
    function refresh_token($refresh_token)
    {
        $url = $this->url . "/oauth/refresh_token?client_key={$this->clientKey}&grant_type=refresh_token&refresh_token={$refresh_token}";
        $data = $this->getJson($url);
        return $data;
    }

    //刷新refresh_token  不需要授权
    function renew_refresh_token($refresh_token)
    {
        $url = $this->url . "/oauth/renew_refresh_token?client_key={$this->clientKey}&refresh_token={$refresh_token}";
        $data = $this->getJson($url);
        return $data;
    }

	//生成client_token  不需要授权 2小时有效
    function client_token()
    {
        $url = $this->url . "/oauth/client_token/";
        $postData = [
            'client_key' => $this->clientKey,
            'client_secret' => $this->clientSecret,
            'grant_type' => 'client_credential',
        ];
        $data = $this->postJson($url, $postData);
        return $data;
    }

    //获取用户信息
    function getUserInfo($open_id, $access_token)
    {
        $url = $this->url . "/oauth/userinfo?open_id={$open_id}&access_token={$access_token}";
        $data = $this->getJson($url);
        return $data;
    }


    //	图片上传-----------------------------------------------------------------------------------------------------------------------------------------------
    function imageUpload($assess_token, $open_id, $image, $name)
    {
        $url = $this->url . "/image/upload/?access_token={$assess_token}&open_id={$open_id}";
        $payload = '';
        $params = "--ABC1234\r\n"
            . "Content-Type: application/x-www-form-urlencoded\r\n"
            . "\r\n"
            . $payload . "\r\n"
            . "--ABC1234\r\n"
            . "Content-Type: image/jpeg\r\n"
            . "Content-Disposition: form-data; name=\"image\"; filename=\"" . $name . "\"\r\n"
            . "\r\n"
            . file_get_contents($image) . "\r\n"
            . "--ABC1234--";
        $first_newline = strpos($params, "\r\n");
        $multipart_boundary = substr($params, 2, $first_newline - 2);
        $request_headers = array();
        $request_headers[] = 'Content-Length: ' . strlen($params);
        $request_headers[] = 'Content-Type: multipart/form-data; boundary=' . $multipart_boundary;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_ENCODING, "");//返回乱码处理
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $reply = curl_exec($ch);
        return json_decode($reply, true);
    }

    // 	视频上传
    function videoUpload($assess_token, $open_id, $video, $name)
    {
        $url = $this->url . "/video/upload/?access_token={$assess_token}&open_id={$open_id}";
        $payload = '';
        $params = "--ABC1234\r\n"
            . "Content-Type: application/x-www-form-urlencoded\r\n"
            . "\r\n"
            . $payload . "\r\n"
            . "--ABC1234\r\n"
            . "Content-Type: video/mp4\r\n"
            . "Content-Disposition: form-data; name=\"video\"; filename=\"" . $name . "\"\r\n"
            . "\r\n"
            . file_get_contents($video) . "\r\n"
            . "--ABC1234--";
        $first_newline = strpos($params, "\r\n");
        $multipart_boundary = substr($params, 2, $first_newline - 2);
        $request_headers = array();
        $request_headers[] = 'Content-Length: ' . strlen($params);
        $request_headers[] = 'Content-Type: multipart/form-data; boundary=' . $multipart_boundary;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_ENCODING, "");//返回乱码处理
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $reply = curl_exec($ch);
        return json_decode($reply, true);
    }

    //	发布视频
    function videoCreate($assess_token, $open_id, $video_id, $img_id, $video_title, $postData=false)
    {
        $url = $this->url . "/video/create/?access_token={$assess_token}&open_id={$open_id}";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        $data = [
            'video_id' => $video_id,
            'text' => $video_title,
        ];
		if($img_id){
			$data['custom_cover_image_url']=$img_id;
		}
		if($postData){
			foreach($postData as $k=>$v){
				if($v){
					$data[$k]=$v;
				}
			}
		}
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_ENCODING, "");//返回乱码处理
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen(json_encode($data)))
        );
        $reply = curl_exec($ch);//CURLOPT_RETURNTRANSFER 不设置  curl_exec 返回TRUE 设置  curl_exec 返回json(此处) 失败都返回FALSE
        curl_close($ch);
        return json_decode($reply, true);
    }
	
	//手机号解密
	function decrypt($mobile){
		$iv=substr($this->clientSecret,0,16);
		if(!empty($mobile)){
			return openssl_decrypt($mobile,'aes-256-cbc',$this->clientSecret,0,$iv);
		}
		return false;
	}
	
	//高德 poid转换
	function POI($amap_id){
		$temToken=$this->client_token();
		$temToken=isset($temToken['data']['access_token']) && !empty($temToken['data']['access_token']) ? $temToken['data']['access_token'] : '';
		$url = $this->url . "/poi/base/query/amap?access_token={$temToken}&amap_id={$amap_id}";
        $data = $this->getJson($url);
        return $data;
	}
	
	
    //get请求
    function getJson($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//为true，则会跟踪爬取重定向页面，否则，不会跟踪重定向页面
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

	//post请求
    function postJson($url, $data = array())
    {
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //超时时间
        curl_setopt($curl, CURLOPT_TIMEOUT, 60);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($curl, CURLOPT_ENCODING, "");//返回乱码处理
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen(json_encode($data)))
        );
        //执行命令
        $json = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        return json_decode($json, true);
    }

}